<template>
    <div class="profile-page">
        <el-card class="profile-card">
            <h2 class="profile-title">主页信息修改申请</h2>
            <el-form
                :model="form"
                label-width="200px"
                style="max-width: 900px; margin: auto"
            >
                <el-form-item label="主页合照名称">
                    <el-input
                        :value="user?.name || ''"
                        readonly
                        disabled
                        placeholder="自动填充为当前主页名称"
                    />
                </el-form-item>
                <el-form-item label="新主页合照图片链接">
                    <el-input
                        v-model="form.newImageUrl"
                        placeholder="请输入图片URL"
                    />
                </el-form-item>

                <el-form-item label="新主页背景视频链接">
                    <el-input
                        v-model="form.newVideoUrl"
                        placeholder="请输入视频URL"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button
                        type="warning"
                        :loading="loading"
                        @click="goToUpload"
                        round
                        >点击前往</el-button
                    >
                    <p>"可以前往该链接上传图片和视频：{{ upload_URL }}"</p>
                </el-form-item>
                <el-form-item>
                    <el-button
                        type="primary"
                        :loading="loading"
                        @click="handleSubmit"
                        round
                        >提交申请</el-button
                    >
                </el-form-item>
            </el-form>
            <el-divider />
            <h2 style="text-align: left; margin-bottom: 16px; color: #409eff">
                审批申请记录
            </h2>
            <el-table :data="pagedApprovals">
                <el-table-column prop="newName" label="新名称" width="150" />
                <el-table-column prop="newImageUrl" label="新图片" width="200">
                    <template #default="scope">
                        <el-image
                            :src="scope.row.newImageUrl"
                            style="width: 4rem; height: 6rem"
                            fit="contain"
                            v-if="scope.row.newImageUrl"
                            :preview-src-list="[scope.row.newImageUrl]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>

                <el-table-column prop="newVideoUrl" label="新视频" width="360">
                    <template #default="scope">
                        <video
                            v-if="scope.row.newVideoUrl"
                            :src="scope.row.newVideoUrl"
                            style="width: 16rem"
                            controls
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                        <el-tag
                            :type="
                                scope.row.status === '已通过'
                                    ? 'success'
                                    : scope.row.status === '未通过'
                                    ? 'danger'
                                    : 'info'
                            "
                        >
                            {{ scope.row.status }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" />
                <el-table-column label="操作" width="120">
                    <template #default="scope">
                        <el-button
                            size="small"
                            @click="openEdit(scope.row)"
                            round
                            >编辑</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <div style="text-align: center; margin: 24px 0">
                <el-pagination
                    background
                    layout="prev, pager, next"
                    :page-size="pageSize"
                    :total="approvals.length"
                    v-model:current-page="currentPage"
                />
            </div>
        </el-card>
        <!-- 编辑对话框 -->
        <el-dialog
            v-model="showEditDialog"
            title="编辑申请"
            width="400px"
            center
        >
            <el-form :model="editForm" label-width="90px">
                <el-form-item label="新名称">
                    <el-input v-model="editForm.newName" />
                </el-form-item>
                <el-form-item label="新图片">
                    <el-input v-model="editForm.newImageUrl" />
                </el-form-item>
                <el-form-item label="新视频">
                    <el-input v-model="editForm.newVideoUrl" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="showEditDialog = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="handleEditSave"
                    :loading="editLoading"
                    >保存</el-button
                >
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
    getUserById,
    createHomeApproval,
    getUserHomeApprovals,
    updateHomeApproval,
} from "./api";
import { upload_URL } from "../config/http.js";
const user = ref(null);
const userId = sessionStorage.getItem("user_id");
if (userId) {
    getUserById(userId).then((data) => {
        user.value = data;
    });
}
const approvals = ref([]);
const form = reactive({
    newName: "",
    newImageUrl: "",
    newVideoUrl: "",
});
const loading = ref(false);
// 分页相关
const currentPage = ref(1);
const pageSize = 3;
const pagedApprovals = computed(() => {
    const start = (currentPage.value - 1) * pageSize;
    return approvals.value.slice(start, start + pageSize);
});
function goToUpload() {
    window.open(upload_URL, "_blank");
}
// 获取当前用户所有审批申请
function fetchApprovals() {
    if (userId) {
        getUserHomeApprovals(userId).then((res) => {
            approvals.value = res;
        });
    }
}

// 提交审批申请
function handleSubmit() {
    if (!form.newImageUrl || !form.newVideoUrl) {
        ElMessage.warning("请填写完整信息");
        return;
    }
    loading.value = true;
    createHomeApproval({
        userId,
        newName: user.value.name,
        newImageUrl: form.newImageUrl,
        newVideoUrl: form.newVideoUrl,
    })
        .then((res) => {
            ElMessage.success(res.message);
            fetchApprovals();
            form.newName = "";
            form.newImageUrl = "";
            form.newVideoUrl = "";
        })
        .catch((err) => {
            ElMessage.error(err.response?.data?.error || "提交失败");
        })
        .finally(() => {
            loading.value = false;
        });
}

const showEditDialog = ref(false);
const editForm = reactive({
    _id: "",
    newName: "",
    newImageUrl: "",
    newVideoUrl: "",
});
const editLoading = ref(false);

function openEdit(row) {
    Object.assign(editForm, row);
    showEditDialog.value = true;
}

function handleEditSave() {
    if (!editForm.newName) {
        ElMessage.warning("新名称不能为空");
        return;
    }
    editLoading.value = true;
    updateHomeApproval(editForm._id, {
        operatorId: userId,
        newName: editForm.newName,
        newImageUrl: editForm.newImageUrl,
        newVideoUrl: editForm.newVideoUrl,
    })
        .then((res) => {
            ElMessage.success(res.message);
            showEditDialog.value = false;
            fetchApprovals();
        })
        .catch((err) => {
            ElMessage.error(err.response?.data?.error || "更新失败");
        })
        .finally(() => {
            editLoading.value = false;
        });
}

onMounted(fetchApprovals);
</script>

<style lang="scss" scoped>
.profile-page {
    display: flex;
    justify-content: center;
    align-items: flex-start;
    width: 100%;
    min-height: 100%;
    background: transparent;
}
.profile-card {
    border-radius: 32px;
    box-shadow: 0 8px 32px 0 rgba(60, 60, 120, 0.12);
    background: #fff;
    animation: mainPop 0.7s cubic-bezier(0.55, 0, 0.1, 1);
    width: 100%;
    height: 100%;
}
.profile-title {
    text-align: center;
    font-size: 2rem;
    font-weight: bold;
    color: #409eff;
    margin-bottom: 24px;
    letter-spacing: 2px;
}
@keyframes mainPop {
    0% {
        opacity: 0;
        transform: scale(0.95);
    }
    100% {
        opacity: 1;
        transform: scale(1);
    }
}
</style>